const app = getApp()
const util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: 1,
    invalidTitle: "提示",
    invalidArea: "请确保您已到达巡检地点！",
    inspectPlanId:[],
    address:'',
    isNFCInspect: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

console.log('options========================', options);
    let inspectPlanId=options.inspectPlanId;
    let address=options.address
    this.setData({
      inspectPlanId:inspectPlanId,
      address:address
    })
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getSchoolUUIDS',
      method: 'POST',
      data: app.globalData.departmentId,
      dataType: 'json',
      success: res => {
        this.setData({
          uuids: res.data.split(",")
        })
      }
    })
    let item = wx.getStorageSync("inspItemList")
    this.setData({
      item
    })
  },
  onShow: function () {
    
    console.log("============", this.data.inspectPlanId)
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getInspectPlanStatusByInspectPlanId',
      method: 'POST',
      data: {
        inspectPlanId: this.data.inspectPlanId,
        // inspectPlanId: "41752,41753,41754,41755,41756,41757,41758",
        schoolId: app.globalData.departmentId
      },
      dataType: 'json',
      success: res => {
        console.log(res.data)
        res.data.sort(function (a, b) {
          return a.checked - b.checked
        })
        let undone=0;
        let done=0;
        res.data.map((item)=>{
          item.checked?done++:undone++
        })
        this.setData({
          ["item.idAndName"]: res.data,
          ["item.undone"]:undone,
          ["item.done"]:done,

        })
        let flag 
        for(let i=0;i<res.data.length;i++){
          if(res.data[i].pass !=0){
            flag = 1
          }
        }
        if(flag ==1){
          this.setData({
            isNFCInspect : 0
          })
        }
      },
      complete: () =>{
        this.setData({
          loading: 0
        })
      }
    })
    //判断是否有和巡检一起执行的nfc巡检
    this.isNFCInspectItem() ;
  },

  showEvent: function (e) {
    let item = this.data.item,
      uncheckedNum = 0,
      checkedNum = 0,
      selectCheck = null
    for (let i = 0; i < item.idAndName.length; i++) {
      if (item.idAndName[i].checked == 0) {
        uncheckedNum++;
      } else {
        checkedNum++;
      }
    }
    if (e.currentTarget.dataset.checked == 0) {
      this.setData({
        isNFCInspect:0
      })
      selectCheck = checkedNum
    } else if (e.currentTarget.dataset.checked == 1) {
      this.setData({
        isNFCInspect:1
      })
      selectCheck = uncheckedNum
    }else{
      this.setData({
        isNFCInspect:1
      })
    }
    let obj = {
      select: selectCheck,
      showChecked: e.currentTarget.dataset.checked
    }
    Object.assign(item, obj)
    this.setData({
      item,
    })
  },


  bindWorkDetail: util.throttle(function (e) {
    console.log(e.currentTarget.dataset)
    let that = this
    if (e.currentTarget.dataset.checked == 0) {


    //pc端测试用 (if条件注释)
      console.log("bleConnect",this.data.bleConnect)
      if (this.data.bleConnect) {  
      wx.navigateTo({
        url: `/pages/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}&categoryName=${e.currentTarget.dataset.categoryname}`
      })
      that.setData({
        fromIndex: 0
      }) 
      return 
      }
      // pc端测试 
      console.log("e.currentTarget.dataset.macaddress",e.currentTarget.dataset.macaddress)
      if (e.currentTarget.dataset.macaddress.indexOf("00000") > -1) {  
        //不需要蓝牙
        wx.navigateTo({
          url: `/pages/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}&categoryName=${e.currentTarget.dataset.categoryname}`
        })
        that.setData({
          fromIndex: 0
        }) 
      } else {
        console.log("need blu")
        if (wx.openBluetoothAdapter) {
          console.log("e.currentTarget.dataset.macaddress",e.currentTarget.dataset.macaddress)
          let blueTooth = e.currentTarget.dataset.macaddress.split(",")
          console.log(blueTooth)
          wx.showLoading({
            title: '正在搜索设备',
            mask: true
          })
          wx.openBluetoothAdapter({ 
            //开启蓝牙 
            fail(res) { 
              wx.showToast({
                title: "请开启蓝牙",
                image: "/images/warning.png",
                duration: 2000
              })
            }, 
            success(res) {
              //允许打开定位
              wx.startBeaconDiscovery({ 
                uuids: that.data.uuids,
                success(res) {
                  let search = 0
                  function doSearch() {
                    search++
                    console.log(search)
                    if (!that.data.stop) {
                      if (search > 5) {
                        that.showModalOwn()
                      } else {
                        setTimeout(doSearch, 900)
                      }
                    }
                  }
                  doSearch()

                  wx.onBeaconUpdate(function (res) {
                    console.log("onBeaconUpdate",res)
                    //加判断条件
                    if (search <= 5) {
                      for (let i = 0; i < res.beacons.length; i++) {
                        let find = 0
                        for (let j = 0; j < blueTooth.length; j++) {
                          if (blueTooth[j].split(":")[0] == res.beacons[i].major && blueTooth[j].split(":")[1] == res.beacons[i].minor) {
                            find = 1
                            break
                          }
                        }

                        if (find == 1) {
                          that.setData({
                            stop: 1,
                            bleConnect: 1
                          })
                          wx.hideLoading()
                          wx.stopBeaconDiscovery()
                          // util.throttle(()=>{
                          wx.navigateTo({
                            url: `/pages/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}&categoryName=${e.currentTarget.dataset.categoryname}`
                          })
                          that.setData({
                            fromIndex: 0
                          })
                          // })
                          return
                        }
                      }
                    }
                  })
                },
                fail(res) {
                  console.log("------------------fail") 
                  that.showModalOwn()
                }
              })
              // wx.getLocation({
              //   type: 'wgs84',
              //   fail: (res) => {
              //     //不允许打开定位
              //     wx.hideLoading() 
              //     wx.getSetting({
              //       success(res) {
              //         //开启小程序内定位
              //         if (res.authSetting["scope.userLocation"] == false) {
              //           wx.showModal({
              //             content: '请允许小程序使用地理位置功能！您可以在【我的】页面点击【设置】按钮快捷设置。',
              //             confirmText: "去设置",
              //             success: res => {
              //               if (res.confirm) {
              //                 wx.switchTab({
              //                   url: '/pages/mine/mine'
              //                 })
              //               }
              //             }
              //           })
              //         } else {
              //           //开启系统设置定位
              //           wx.getSystemInfo({
              //             success: res => {
              //               if (res.platform == "ios") {
              //                 that.setData({
              //                   locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
              //                 })
              //               }
              //               wx.showModal({
              //                 title: '未允许使用地理位置',
              //                 content: that.data.locationContent,
              //                 showCancel: false
              //               })
              //             },
              //             fail: res => {
              //               wx.showModal({
              //                 title: '未允许使用地理位置',
              //                 content: that.data.locationContent,
              //                 showCancel: false
              //               })
              //             }
              //           })
              //         }

              //       }
              //     })
              //   }, 
              //   success: res => {
              //     //允许打开定位
              //     wx.startBeaconDiscovery({
              //       uuids: that.data.uuids,
              //       success(res) {
              //         let search = 0
              //         function doSearch() {
              //           search++
              //           console.log(search)
              //           if (!that.data.stop) {
              //             if (search > 5) {
              //               that.showModalOwn()
              //             } else {
              //               setTimeout(doSearch, 900)
              //             }
              //           }
              //         }
              //         doSearch()

              //         wx.onBeaconUpdate(function (res) {
              //           console.log("onBeaconUpdate",res.data)
              //           //加判断条件
              //           if (search <= 5) {
              //             for (let i = 0; i < res.beacons.length; i++) {
              //               let find = 0
              //               for (let j = 0; j < blueTooth.length; j++) {
              //                 if (blueTooth[j].split(":")[0] == res.beacons[i].major && blueTooth[j].split(":")[1] == res.beacons[i].minor) {
              //                   find = 1
              //                   break
              //                 }
              //               }

              //               if (find == 1) {
              //                 that.setData({
              //                   stop: 1,
              //                   bleConnect: 1
              //                 })
              //                 wx.hideLoading()
              //                 wx.stopBeaconDiscovery()
              //                 // util.throttle(()=>{
              //                 wx.navigateTo({
              //                   url: `/pages/workInspectDetail/workInspectDetail?inspectPlanId=${e.currentTarget.dataset.inspectplanid}&categoryId=${e.currentTarget.dataset.categoryid}&checked=${e.currentTarget.dataset.checked}&address=${e.currentTarget.dataset.address}&className=${e.currentTarget.dataset.classname}`
              //                 })
              //                 that.setData({
              //                   fromIndex: 0
              //                 })
              //                 // })
              //                 return
              //               }
              //             }
              //           }
              //         })
              //       },
              //       fail(res) {
              //         console.log("------------------fail")
              //         that.showModalOwn()
              //       }
              //     })
              //   },
              // })
            }
          })

        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
          })
        }
      }

     } else {
      wx.navigateTo({
        url: '/pages/workInspectHistory/workInspectHistory?inspectPlanId=' + e.currentTarget.dataset.inspectplanid + '&categoryId=' + e.currentTarget.dataset.categoryid + '&checked=' + e.currentTarget.dataset.checked
      })
      that.setData({
        fromIndex: 0
      })
    }
  }),

  //判断该计划里面是否有nfc巡检任务
  isNFCInspectItem:function(e){
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/isNFCInspectItem',
      method: 'POST',
      dataType: 'json',
      data: {
        schoolId : parseInt(app.globalData.departmentId) ,
        address : this.data.address
      },
      success: res => {
        console.log(res.data)
        let flag = 0 
        let nfcInspectItemList = []
        let categoryId = wx.getStorageSync('inspItemList').categoryId
        for(let i=0;i<res.data.length;i++){
          if(res.data[i].type == 2 && res.data[i].categoryId == categoryId){
            flag = 1 
            nfcInspectItemList.push({
              nfcheckItem : res.data[i].item 
            })
          }
        }
        if(flag == 1){
          this.setData({
            nfcInspectItemList:nfcInspectItemList,
            isNFCInspect : 1
          })
        }
        wx.request({
          url: app.inspectUrl + '/WeChat/weChatSystem/getNFCommitStatus',
          method: 'POST',
          dataType: 'json',
          data: {
            inspectPlanId: this.data.inspectPlanId,
            schoolId: app.globalData.departmentId,
            address:this.data.address
          },
          success: res2 => {
            console.log(res2.data)
            for(let i=0;i<this.data.nfcInspectItemList.length;i++){
              for(let j = 0;j<res2.data.length;j++){
                if(this.data.nfcInspectItemList[i].nfcheckItem == res2.data[j].item){
                  this.data.nfcInspectItemList[i].status = res2.data[j].status
                }
              }
            }
            this.setData({
              nfcInspectItemList : this.data.nfcInspectItemList
            })
          }
        })
      }
    })
  },
  
  //跳转nfc感应界面
  toNFCPage:function(e){
    //跳转nfc感应界面
    wx.navigateTo({
      url: `/subpages/pages/nfcResponse/nfcResponse?inspectPlanId=`+this.data.inspectPlanId,
    })
  },

  showModalOwn: function () {
    let that = this
    wx.hideLoading()
    wx.offBeaconUpdate()
    wx.stopBeaconDiscovery()
    wx.showModal({
      title: that.data.invalidTitle,
      content: that.data.invalidArea,
      showCancel: false
    })
  },

  onHide: function () {
    this.setData({
      stop: 1
    })
    wx.offBeaconUpdate()
    wx.stopBeaconDiscovery()
  },


  onUnload: function () {
    this.setData({
      stop: 1
    })
    wx.offBeaconUpdate()
    wx.stopBeaconDiscovery()
  },

})
